//
//  CalendarContainerView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/15.
//

import Foundation
import FSCalendar
import SwiftUI

// MARK: - FSCalendar 封装视图
struct CalendarContainerView<Content: View>: UIViewRepresentable {
    let yearOrmonth: String  //"yyyy-MM"
    let events: [String: Any]? //标记事件
    let dayView: (CalendarBean) -> Content

    
    // 日期格式化工具
    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter
    }
    
    
    func makeUIView(context: Context) -> FSCalendar {
        let calendar = FSCalendar()
        
        // 基础配置
        calendar.dataSource = context.coordinator
        calendar.delegate = context.coordinator
        calendar.scrollDirection = .vertical
        calendar.scrollEnabled = false // 禁用滚动
        calendar.allowsSelection = false // 禁用选择
        calendar.scope = .month
        calendar.placeholderType = .none // 隐藏非本月日期
        //            .none：完全隐藏占位日期
        //            .fillHeadTail：仅显示前后补齐行数的日期（默认）
        //            .fillSixRows：强制显示六行日期
        
        // 外观配置
        calendar.appearance.headerTitleColor = .clear
        calendar.appearance.headerMinimumDissolvedAlpha = 0
        calendar.headerHeight = 0 // 隐藏头部
        calendar.appearance.titleFont = .systemFont(ofSize: 12)
        calendar.appearance.titleDefaultColor = .clear // 隐藏默认日期文字
        
        // 设置星期标题本地化格式为中文
        calendar.appearance.weekdayTextColor = .bgNormalText2
        calendar.calendarWeekdayView.weekdayLabels.forEach { label in
            label.font = UIFont.systemFont(ofSize: 12)
        }
        let locale = Locale(identifier: "zh_CN")
        calendar.locale = locale
        
        // 设置当前显示月份
        if let date = dateFormatter.date(from: yearOrmonth) {
            calendar.currentPage = date
            calendar.firstWeekday = 2 // 周一为一周的第一天
            calendar.setCurrentPage(date, animated: false)
        }
        
        // 取消今日的红色圆形样式
        calendar.appearance.todayColor = nil
        calendar.appearance.selectionColor = nil
        
        // 注册自定义单元格
        calendar.register(FSCalendarCell.self, forCellReuseIdentifier: "cell")
        return calendar
    }
    
    func updateUIView(_ uiView: FSCalendar, context: Context) {
        uiView.reloadData()
    }
    
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self, dayView : dayView)
    }
    
    // MARK: - Coordinator 处理日历逻辑
    class Coordinator: NSObject, FSCalendarDataSource, FSCalendarDelegate {
        let parent: CalendarContainerView
        let dayView: (CalendarBean) -> Content

        private let dayFormatter: DateFormatter = {
            let formatter = DateFormatter()
            formatter.dateFormat = "yyyy-MM-dd"
            return formatter
        }()
        
        init(parent: CalendarContainerView, dayView: @escaping (CalendarBean) -> Content) {
            self.parent = parent
            self.dayView = dayView
        }
        
        // MARK: 数据源方法
        func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
            let cell = calendar.dequeueReusableCell(withIdentifier: "cell", for: date, at: position)
            
            // 清理旧视图
            cell.contentView.subviews.forEach { $0.removeFromSuperview() }
            
            // 日期处理
            let day = Calendar.current.component(.day, from: date)
            let isToday = Calendar.current.isDateInToday(date)
            let dateKey = dayFormatter.string(from: date)
            
            // 创建 SwiftUI 视图
            let calendarBean = CalendarBean()
            calendarBean.day = day
            calendarBean.isToday = isToday
            calendarBean.event = parent.events?[dateKey]
           
            // 转换为 UIKit 视图
            let hostingController = UIHostingController(rootView: dayView(calendarBean))
            //cell.contentView.bounds 设置了间距
            //            hostingController.view.frame = cell.contentView.bounds
            //根据cell.contentView.bounds的宽高来设置
            let width = cell.contentView.bounds.width
            //            let height = cell.contentView.bounds.height //该高度好像偏小，统一用宽度的
            hostingController.view.frame = CGRect(x: 0, y: 0, width : width, height: width)
            hostingController.view.backgroundColor = .clear
            
            // 添加视图到单元格
            cell.contentView.addSubview(hostingController.view)
            return cell
        }
        
        // MARK: 日期范围限制
        func minimumDate(for calendar: FSCalendar) -> Date {
            return parent.dateFormatter.date(from: parent.yearOrmonth) ?? Date()
        }
        
        func maximumDate(for calendar: FSCalendar) -> Date {
            guard let date = parent.dateFormatter.date(from: parent.yearOrmonth) else {
                return Date()
            }
            return Calendar.current.date(byAdding: .month, value: 1, to: date) ?? Date()
        }
    }
}
